package com.example.helloservicecontroller;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

import com.example.helloandroid.IMessengerService;
import com.example.helloandroid.IRemoteService;

public class HelloServiceController extends Activity {
	private static final String TAG = "HelloServiceController";
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		Log.i(TAG, "onCreate()");
        setContentView(R.layout.main);
        bindService(new Intent(IMessengerService.class.getName()), mMessengerConnection, Context.BIND_AUTO_CREATE);
        bindService(new Intent(IRemoteService.class.getName()), mRemoteConnection, Context.BIND_AUTO_CREATE);
    }
    
	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log.i(TAG, "onDestory()");
		unbindService(mMessengerConnection);
		unbindService(mRemoteConnection);
	}
	
	private ServiceConnection mRemoteConnection = new ServiceConnection() {
		private static final String TAG = "RemoteConnection";

		public void onServiceConnected(ComponentName className, IBinder service) {
			Log.i(TAG, "onServiceConnected()");
			IRemoteService remoteService = IRemoteService.Stub
					.asInterface(service);
			try {
				remoteService.showNotification("onServiceConnected()");
			} catch (RemoteException e) {
				e.printStackTrace();
			}
		}

		public void onServiceDisconnected(ComponentName className) {
			Log.i(TAG, "onServiceDisconnected()");
		}
	};
	
	private ServiceConnection mMessengerConnection = new ServiceConnection() {
		private static final String TAG = "MessengerConnection";

		public void onServiceConnected(ComponentName className, IBinder service) {
			Log.i(TAG, "onServiceConnected()");
			Messenger messengerService = new Messenger(service);
			try {
				Bundle b = new Bundle();
				b.putString("msg", "onServiceConnected");
				messengerService.send(Message.obtain(null, IMessengerService.MSG_SHOW_NOTIFICATION, b));
			} catch (RemoteException e) {
				e.printStackTrace();
			}
		}

		public void onServiceDisconnected(ComponentName className) {
			Log.i(TAG, "onServiceDisconnected()");
		}
	};

}